﻿<template>
	<div class="caiJiLog-container">
		<el-row>
			<el-col :span="12">
				<div>
					<SelectionArea class="container red" :options="{ selectables: '.selectable' }" @move="onMove" @start="onStart">
						<div
							style="display: flex; align-items: center; align-content: center; text-align: center; justify-content: center"
							v-for="item of tableData"
							:key="item.id"
							:data-key="item.id"
							class="selectable"
							:class="{ selected: selected.has(item.id) }"
						>
							<el-image
								style="width: 50px; height: 50px"
								:src="'data:image/jpeg;base64,' + item.imageBase64"
								:zoom-rate="1.2"
								:max-scale="7"
								:min-scale="0.2"
								:preview-src-list="['data:image/jpeg;base64,' + item.imageBase64]"
								:initial-index="0"
								:preview-teleported="true"
								fit="cover"
							/>
						</div>
					</SelectionArea>
				</div>
				<div>
					<el-row>
						<el-col :span="4" style="text-align: right; padding-right: 10px">人员查询</el-col>
						<el-col :span="6"
							><el-input v-model="SearchInput" placeholder="请输入姓名">
								<template #append>
									<el-button :icon="Search" type="primary" circle @click="handleEmpQuery" />
								</template> </el-input
						></el-col>
						<el-col :span="4" style="text-align: right; padding-right: 10px">人员选择</el-col>
						<el-col :span="6">
							<el-select v-model="SelectValue" placeholder="请选择" size="small" style="width: 240px">
								<el-option v-for="item in SelectData" :key="item" :label="item.projectIdName + '---' + item.name" :value="item" /> </el-select
						></el-col>
					</el-row>
					<el-row style="margin-top: 10px">
						<el-col :span="4" style="text-align: right; padding-right: 10px">分组编号</el-col>
						<el-col :span="6"><el-input-number size="small" v-model="GroupNum" :min="1" :max="10" /></el-col>
						<el-col :span="4" style="text-align: right; padding-right: 10px">进出方向</el-col>
						<el-col :span="6">
							<el-radio-group v-model="radio">
								<el-radio :value="1" border>进</el-radio>
								<el-radio :value="2" border>出</el-radio>
							</el-radio-group></el-col
						>
					</el-row>
					<el-row style="margin-top: 10px">
						<el-col :span="4" style="text-align: right; padding-right: 10px">已选记录</el-col>
						<el-col :span="6"
							><el-tag type="primary">{{ selectedArray.length }}</el-tag></el-col
						>
						<el-col :span="4"></el-col>
						<el-col :span="10">
							<el-button type="primary" @click="onAddToGroup">添加到分组</el-button>
							<el-button type="primary" @click="saveGroup">保存该方案</el-button>
							<el-button type="danger" @click="delCaiJiLog">清空采集数据</el-button>
						</el-col>
					</el-row>
				</div>
			</el-col>
			<el-col :span="12">
				<div v-for="item in SelectGroup" :key="item">
					分组: {{ item.groupNum }}, 方向: {{ getRadioDirection(item.radio) }}
					<div style="display: flex; flex-direction: row; flex-wrap: wrap">
						<div v-for="subitem in item.items" :key="subitem" style="margin-left: 2px">
							<el-image
								style="width: 50px; height: 50px"
								:src="'data:image/jpeg;base64,' + subitem.imageBase64"
								:zoom-rate="1.2"
								:max-scale="7"
								:min-scale="0.2"
								:preview-src-list="['data:image/jpeg;base64,' + subitem.imageBase64]"
								:initial-index="0"
								:preview-teleported="true"
								fit="cover"
							/>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts" setup="" name="caiJiLog">
import { ref, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { pageCaiJiLog, deleteCaiJiLog, deleteCaiJiLogALL } from '/@/api/main/caiJiLog';
import { pageEmployee } from '/@/api/main/employee';
import { reactive } from 'vue';
import { SelectionArea, SelectionEvent } from '@viselect/vue';
import { Search } from '@element-plus/icons-vue';
import { addCaiJiPhotosbatch } from '/@/api/main/caiJiPhotos';

const GroupNum = ref(1);
const SearchInput = ref('');
const SelectValue = ref({}) as any;
const SelectData = ref<any>([]);
const SelectGroup = ref<any>([]);
const radio = ref(1);

const loading = ref(false);
const tableData = ref<any>([]);
const queryParams = ref<any>({});
const tableParams = ref({
	page: 1,
	pageSize: 2000,
	field: 'createTime', // 默认的排序字段
	order: 'descending', // 排序方向
	descstr: 'descending', // 降序排序的关键字符
	total: 0 as any,
});

// CaiJiPhotos 类定义
class CaiJiPhotos {
	constructor(
		public employeeId: number,
		public clothesGroup: number,
		public direction: number,
		public photos: string[]
	) {}
}

const selected = reactive<Set<number>>(new Set());
// 计算属性，实时获取选中的 ID 数组
const selectedArray = computed(() => Array.from(selected));

const getRadioDirection = (radio: any) => {
	if (radio === 1) return '进';
	if (radio === 2) return '出';
	return '未知方向';
};

const extractIds = (els: Element[]): number[] => {
	return els
		.map((v) => v.getAttribute('data-key'))
		.filter(Boolean)
		.map(Number);
};

const onStart = ({ event, selection }: SelectionEvent): void => {
	if (!event?.ctrlKey && !event?.metaKey) {
		selection.clearSelection();
		selected.clear();
	}
};

const onMove = ({
	store: {
		changed: { added, removed },
	},
}: SelectionEvent): void => {
	extractIds(added).forEach((id) => selected.add(id));
	extractIds(removed).forEach((id) => selected.delete(id));
};

// 添加到分组
const onAddToGroup = async () => {
	// const tableData = ref<any>([]);  值为:[{"id": 582982139146309,"projectId": 581557763747909},{"id": 582982121902149,"projectId": 581557763747909},]
	// selectedArray 值为:[582982139146309,582982130524229, 582982121902149]
	// const SelectGroup = ref<any>([]);

	// 分组值GroupNum.value
	// 进出方向值radio.value
	//console.log(selectedArray.value);

	if (selectedArray.value.length <= 0) {
		ElMessage.error('未选择任何图片');
		return;
	}
	if (SelectValue?.value?.id == undefined) {
		ElMessage.error('未选择人员');
		return;
	}

	/*

	// Step 1: 删除 tableData 中 id 存在于 selectedArray 中的项，并收集这些项
	const idsToRemove = new Set(selectedArray.value);

	// 找到要删除的项
	const itemsToRemove = tableData.value.filter((item: any) => idsToRemove.has(item.id));

	// 更新 tableData，保留不被删除的项
	const remainingItems = tableData.value.filter((item: any) => !idsToRemove.has(item.id));
	tableData.value = remainingItems; // 更新 tableData

	// Step 2: 检查 SelectGroup 中是否存在与 GroupNum.value 和 radio.value 相同的项
	const groupKey = `${GroupNum.value}-${radio.value}`;
	let group = SelectGroup.value.find((existingGroup: any) => existingGroup.key === groupKey);

	if (group) {
		// 存在，向现有分组添加删除的项
		group.items.push(...itemsToRemove.map((item: any) => ({ ...item }))); // 使用 spread operator 确保是同一结构
	} else {
		// 不存在，新增分组并将 itemsToRemove 添加进去
		const newGroup = {
			key: groupKey,
			items: itemsToRemove.map((item: any) => ({ ...item })), // 使用 spread operator 确保是同一结构
		};
		SelectGroup.value.push(newGroup);
	}
  
  */

	// Step 1: 收集需要删除的项
	const idsToRemove = new Set(selectedArray.value);
	const itemsToRemove = tableData.value.filter((item: any) => idsToRemove.has(item.id));
	tableData.value = tableData.value.filter((item: any) => !idsToRemove.has(item.id));

	// Step 2: 检查 SelectGroup 中是否存在相同的组
	const groupNum = GroupNum.value; // 从 ref 中获取分组编号
	const radioValue = radio.value; // 从 ref 中获取当前选择的 radio 值

	// 查找是否存在与 groupNum 和 radioValue 相同的项
	let group = SelectGroup.value.find((existingGroup: any) => existingGroup.groupNum === groupNum && existingGroup.radio === radioValue);

	if (group) {
		// 存在，向现有分组添加删除的项
		group.items.push(...itemsToRemove.map((item: any) => ({ ...item }))); // 确保是同一结构
	} else {
		// 不存在，新增分组并将 itemsToRemove 添加进去
		const newGroup = {
			groupNum, // 存储分组编号
			radio: radioValue, // 存储当前 radio 值
			items: itemsToRemove.map((item: any) => ({ ...item })), // 添加已删除的项
		};
		SelectGroup.value.push(newGroup);
	}

	//console.log(SelectGroup.value);
	selected.clear();
	ElMessage.success('成功添加到分组');
};

//写saveGroup方法
const saveGroup = async () => {
	loading.value = true;
	if (SelectGroup.value.length <= 0) {
		ElMessage.error('未分组');
		return;
	}
	if (SelectValue?.value?.id == undefined) {
		ElMessage.error('未选择人员');
		return;
	}
	// 转换操作
	const convertedData: any[] = []; // 使用 any 数组，不指定具体类型
	SelectGroup.value.forEach((group: any) => {
		if (group.items && group.items.length > 0) {
			// const photos: string[] = group.items.map((item: any) => item.imageBase64);
			const photos: string[] = group.items.map((item: any) => item.id);
			const employeeId = SelectValue?.value?.id;
			convertedData.push(new CaiJiPhotos(employeeId, group.groupNum, group.radio, photos));
		}
	});

	console.log(convertedData);
	await addCaiJiPhotosbatch(convertedData);
	ElMessage.success('方案已保存');
	loading.value = false;
};

const handleEmpQuery = async () => {
	if (SearchInput.value == '') {
		ElMessage.error('请输入姓名再查询');
		return;
	}

	queryParams.value = {
		name: SearchInput.value,
		page: 1,
		pageSize: 2000,
	};

	loading.value = true;
	var res = await pageEmployee(Object.assign(queryParams.value, tableParams.value));
	SelectData.value = res.data.result?.items ?? [];
	ElMessage.success('查询成功,请选择');
	if (SelectData.value.length > 0) {
		SelectValue.value = SelectData.value[0];
	}
	loading.value = false;
};

// 查询操作
const handleQuery = async () => {
	loading.value = true;
	var res = await pageCaiJiLog(Object.assign(queryParams.value, tableParams.value));
	tableData.value = res.data.result?.items ?? [];
	tableParams.value.total = res.data.result?.total;
	loading.value = false;
};

// 删除
const delCaiJiLog = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗,清空后需要重新采集?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			//await deleteCaiJiLog(row);  deleteCaiJiLogALL
			await deleteCaiJiLogALL();
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

handleQuery();
</script>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>

<style scoped>
.container {
	/* display: -webkit-box;
	display: -ms-flexbox; */
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	border: 2px solid rgba(66, 68, 90, 0.075);
	border-radius: 0.15em;
	padding: 1em 0;
	user-select: none;
	margin-bottom: 3em;
}
.container.red {
	/* display: grid; */
	/* grid-template-columns: repeat(15, 1fr); */
	/* grid-gap: 0.4em; */

	align-items: flex-start;
	justify-content: flex-start;
	max-height: 600px;
	overflow: auto;
	padding: 0.5em;
	margin-bottom: 3em;
}
.container.red > div {
	/* margin: 0; */
}

.container div {
	height: 6em;
	width: 6em;
	margin: 0.2em;
	background: rgba(66, 68, 90, 0.075);
	/* border: 2px solid transparent; */
	border: 1px solid rgba(66, 68, 90, 0.075);
	border-radius: 0.15em;
	cursor: pointer;
}
.container.green div.selected {
	background: hsl(100, 80%, 65%);
	border: 2px solid rgba(0, 0, 0, 0.075);
}
.container.blue div.selected {
	background: hsl(150, 80%, 65%);
	border: 2px solid rgba(0, 0, 0, 0.075);
}
.container.red div.selected {
	background: hsl(200, 80%, 65%);
	border: 2px solid rgba(0, 0, 0, 0.075);
}
.selection-area {
	background: rgba(46, 115, 252, 0.11);
	border: 1px solid rgba(98, 155, 255, 0.85);
	border-radius: 0.15em;
}
</style>
